import { useLogin, useGetinfo, useLogout } from '~/api/manager/index'
import type { LoginParmas } from '~/api/manager/type'
import { userType } from './types/user'
const cookie = useCookie()
//选项式api写法
export const useUserStore = defineStore('useUserStore', {
  // 定义数据
  state(): userType {
    return {
      userInfo: {}, // 用户信息
      menus: [], //菜单数组
      ruleNames: [], //权限名称
      hasGetInfo: false,
    }
  },
  actions: {
    //登录方法
    useLoginfn(formParmas: LoginParmas) {
      return new Promise((resolve, reject) => {
        useLogin(formParmas)
          .then((resp) => {
            cookie.set('token', resp.token) //存起token
            resolve(resp)
          })
          .catch((err) => reject(err))
      })
    },
    // 获取当前用户信息
    useGetUserfn() {
      return new Promise((resolve, reject) => {
        useGetinfo()
          .then((resp) => {
            let { menus, ruleNames } = resp
            this.$patch({
              userInfo: resp,
              menus,
              ruleNames,
            })
            resolve(resp)
          })
          .catch((err) => reject(err))
      })
    },
    //退出登录方法
    async useLogoutfn() {
      await useLogout().finally(() => {
        this.userInfo = {} //清除用户信息
        cookie.remove('token') //清除token
        this.hasGetInfo = false
      })
    },
  },
  getters: {},
})
